<?php

namespace App\Store\Services\Excel;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

class DownloadTemp implements FromCollection,  WithEvents, WithStyles,WithColumnFormatting
{

    //公共模板下载
    private $row;
    private $options;
    private $datawith;
    private $dataTypes;

    private $customColor;

    public function __construct(array $row, array $options = [], array $datawith = [],array $customColor=[],array $dataTypes=[])
    {
        $this->row = $row;
        $this->options = $options;
        $this->datawith = $datawith;
        $this->customColor= $customColor;
        $this->dataTypes = $dataTypes;
    }

    // Implement data type formatting
    public function columnFormats(): array
    {
        $formats = [];

        // Handle data types
        foreach ($this->dataTypes as $column => $type) {
            if ($type === 'string') {
                $formats[$column] = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT;
            }
        }

        return $formats;
    }
    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $row = $this->row;

        return collect($row);
    }
    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                foreach ($this->options as $key => $val) {
                    $event->sheet->getDataValidation($key . '2:' . $key . '1000')->setType(DataValidation::TYPE_LIST)->setShowDropDown(true)->setFormula1(sprintf('"%s"', implode(',', $val)));
                }
            },
        ];
    }

    public function styles(Worksheet $sheet)
    {
        foreach($this->generateColumnRange('A',$sheet->getHighestDatacolumn())as $columnID){
            $sheet->getColumnDimension($columnID)->setAutosize(true);
        }

//        // 如果设置了宽度就走设置的宽度
//        if (count($this->datawith)) {
//            foreach ($this->datawith as $key => $val) {
//                $sheet->getColumnDimension($key)->setAutosize(false)->setWidth($val);
//
//            }
//        }

        $lastrow = $this->row[count($this->row)-1];
        $j = 1;
        foreach ($lastrow as $k=>$value)
        {
            if($value == '条码')
            {
                $s = $this->titlecount($j);
                $sheet->getColumnDimension($s)->setWidth('25');
            }
        }


        $titlecount=$this->titlecount();

        $sheet->getStyle('A1:'.$titlecount.'1')->applyFromArray(['alignment' => ['horizontal' => 'center']]);
        $sheet->getStyle('A1:'.$titlecount.'1')->getFont()->setSize(10)->setBold(true);

        // $sheet->getStyle('A1:C1')->getFont()->getColor()
        //     ->setRGB('FF0000');

        $sheet->getRowDimension('1')->setRowHeight(25);
        $sheet->getStyle('A1:'.$titlecount.'1')->getAlignment()->setVertical('center');
        $sheet->getStyle('A1:'.$titlecount.'1')->getFill()
            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
            ->getStartColor()->setRGB('9BC2E6');
        $customColor =$this->customColor;
        if(!empty($customColor)){
            foreach ($customColor as $column)
                $sheet->getStyle($column.'1')
                    ->getFont()
                    ->getColor()
                    ->setARGB('FFFF0000');
        }


        foreach ($this->dataTypes as $column => $type) {
            if ($type === 'string') {
                $sheet->getStyle($column.":".$column)
                    ->getNumberFormat()
                    ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_TEXT);
            }
        }
    }



    protected function titlecount($number = ''){
        if(empty($number))
        {
            $number = count($this->row[0]);
        }
        if(ceil($number/26)==1){
            $remainder = $number % 26; // 1-26
            $excelColumn = $remainder>0 ?chr($remainder + 64):'Z';
        }elseif(ceil($number/26)==2){
            $remainder = $number % 26; // 1-26
            $excelColumn = $remainder>0 ?'A'.chr($remainder + 64):'AZ';
        }elseif(ceil($number/26)==3){
            $remainder = $number % 26; // 1-26
            $excelColumn = $remainder>0 ?'B'.chr($remainder + 64):'BZ';
        }

        return $excelColumn;

    }



    public function generateColumnRange($start, $end): array
    {
        $columns = [];

        // 单字母列标识符
        for ($i = ord($start); $i <= ord('Z'); $i++) {
            $columns[] = chr($i);
        }

        // 双字母列标识符
        if (strlen($end) == 2) {
            $firstLetter = substr($end, 0, 1);
            $secondLetter = substr($end, 1, 1);

            for ($i = ord('A'); $i <= ord($firstLetter); $i++) {
                for ($j = ord('A'); $j <= ord($secondLetter); $j++) {
                    $columns[] = chr($i) . chr($j);
                }
            }
        }

        // 返回从 'A' 到 'AZ' 的列标识符数组
        return array_slice($columns, 0, array_search($end, $columns) + 1);
    }

}
